package com.btioe.yugong.comsumer;

import cn.hutool.core.date.DateUtil;
import com.btioe.yugong.comsumer.mysql.ConnectionPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.sql.Connection;
import java.sql.Statement;
import java.util.Date;
import java.util.Queue;

@Slf4j
public class SqlExcuter implements Runnable {
    static final String DB_URL_FORMAT = "jdbc:mysql://%s:3306/%s";
    String dbUrl;
    String dbName;
    String userName;
    String passrod;
    Queue<String> queue;

    public SqlExcuter(String dbUrl,
                      String dbName,
                      String userName,
                      String passrod,
                      Queue<String> queue) {
        this.dbUrl = dbUrl;
        this.dbName = dbName;
        this.userName = userName;
        this.passrod = passrod;
        this.queue = queue;
    }

    @Override
    public void run() {
        String url = String.format(DB_URL_FORMAT, dbUrl, dbName);
        try {
            ConnectionPool connPool = new ConnectionPool("com.mysql.cj.jdbc.Driver",
                    url,
                    userName,
                    passrod);
            connPool.createPool();

            while (true) {
                String poll = "";
                try {
                    poll = queue.poll();
                    if (StringUtils.isEmpty(poll)) {
                        Thread.sleep(1000);
                        continue;
                    }
                } catch (Exception e) {
                    log.error("", e);
                    continue;
                }
                Connection connection = null;
                try {

                    connection = connPool.getConnection();
                    Statement statement = connection.createStatement();
                    statement.execute(poll);
                    int updateCount = statement.getUpdateCount();
                    log.info("{}执行sql({}):{}", DateUtil.formatDateTime(new Date()), updateCount, poll);
                    if (updateCount < 1) {
                        log.warn("影响行数0", poll);
                    }
                    connPool.returnConnection(connection);
                } catch (Exception e) {
                    log.error("{},{}", DateUtil.formatDateTime(new Date()), poll, e);
                } finally {
                    connPool.returnConnection(connection);
                }
            }
        } catch (Exception e) {
            log.error("", e);
        }
        log.warn("end");
    }
}
